﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Bike.Forms.Customers;
using Bike.Biz;
using Bike.Repository.Models;
using Bike.Repository;
using Telerik.WinControls.UI;
using System.Data.Objects.DataClasses;

namespace Bike.Forms.Warehouses
{
    public partial class WarehouseAddIemForm : BikeForm
    {
        private class OrderDetailItem
        {
            public int Index { get; set; }
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public decimal Total { get; set; }
            public decimal Price { get; set; }
            public int Quantity { get; set; }
        }
        bool isUpdating;
        List<OrderDetailItem> _details = new List<OrderDetailItem>();
        IEnumerable<Product> _products;
        OrderDetailItem edititem;
        public int ImportType { get; set; }
        protected IEnumerable<Product> Products
        {
            get
            {
                if (_products == null)
                {
                    ProductService service = new ProductService();
                    _products = service.GetAllItems();
                }
                return _products;
            }
        }
        public WarehouseAddIemForm()
        {
            
            InitializeComponent();
            LoadCustomers();
            UIHelper.DisplayProducts(this.Products, ddlProducts);
            ReloadDetails();
            
        }
        private void ReloadDetails()
        {
            grvDetails.DataSource = null;
            grvDetails.DataSource = this._details;
         
        }
        private void LoadCustomers()
        {
            CustomerService service = new CustomerService();
            var items = service.GetCustomer(CustomerTypes.Suppliers);
            UIHelper.DisplayCustomer(items, ddlCustomer);
           
        }

        private void bntClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void radCalendar1_SelectionChanged(object sender, EventArgs e)
        {

        }

        private void bntAddCustomer_Click(object sender, EventArgs e)
        {
            AddCustomerForm form = new AddCustomerForm(Repository.Models.CustomerTypes.Suppliers);
            form.OnAdded += new OnAddedCustomer(form_OnAdded);
            form.ShowDialog();

        }

        void form_OnAdded(Repository.Customer customer)
        {
            LoadCustomers();
        }

        private void grvDetails_CellEditorInitialized(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            if (e.Column.Name == "ddlProduct")
            {
                
               var editor = e.ActiveEditor as RadDropDownListEditor;
                var editorElement = editor.EditorElement as RadDropDownListEditorElement;
                editorElement.DataSource = Products;
                editorElement.DisplayMember = "Name";
                editorElement.ValueMember = "Name";
                editorElement.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown;
                editorElement.SelectedValueChanged += new Telerik.WinControls.UI.Data.ValueChangedEventHandler(editorElement_SelectedValueChanged);
            }
        }

        void editorElement_SelectedValueChanged(object sender, Telerik.WinControls.UI.Data.ValueChangedEventArgs e)
        {
            
        }

        private void grvDetails_CellValuePushed(object sender, GridViewCellValueEventArgs e)
        {
            ShowInfomationBox("sss", "sss");
        }

        private void grvDetails_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            
            
            
        }

        private void grvDetails_Click(object sender, EventArgs e)
        {

        }

        private void bntAddOrUpdate_Click(object sender, EventArgs e)
        {
            if (isUpdating)
            {

                edititem.ProductName = ddlProducts.Text;
                edititem.ProductId = Convert.ToInt32(ddlProducts.SelectedValue);
                edititem.Price = Convert.ToDecimal(txtCost.Text);
                edititem.Quantity = Convert.ToInt32(txtQuantity.Value);
                edititem.Total = (Convert.ToDecimal(txtCost.Text) * (int)txtQuantity.Value);
                isUpdating = false;
                bntAddOrUpdate.Text = "Thêm sản phẩm";
            }
            else
            {

                _details.Add(new OrderDetailItem()
                {
                    Index = _details.Count + 1,
                    ProductName = ddlProducts.Text,
                    ProductId = Convert.ToInt32(ddlProducts.SelectedValue),
                    Price = Convert.ToDecimal(txtCost.Text),
                    Quantity = Convert.ToInt32(txtQuantity.Value),
                    Total = (Convert.ToDecimal(txtCost.Text) * (int)txtQuantity.Value)

                });
            }
            ResetForm(false);
            lblTotal.Text = _details.Sum(p => p.Total).ToString("N");
        }

        private void ResetForm(bool resetAll)
        {
            if (resetAll)
            {
                _details.Clear();
                txtOrderCode.Text = string.Empty;

                bntAddOrUpdate.Enabled = false;
                ddlCustomer.Items[0].Selected = true;
                ddlProducts.Items[0].Selected = true;
            }
            else
            {
                bntImport.Enabled = _details.Count > 0;
                
            }
            txtQuantity.Value = 1;
            txtCost.Text = "0";
            ReloadDetails();
        }

        private void grvDetails_CellClick(object sender, GridViewCellEventArgs e)
        {
            try
            {
                ShowUpdate(Convert.ToInt32(grvDetails.CurrentRow.Cells[0].Value) - 1);
            }
            catch (Exception)
            {
                
                
            }
            
        }

        private void ShowUpdate(int index)
        {
            edititem = _details[index];
            ddlProducts.SelectedValue = edititem.ProductId;
            txtCost.Text = edititem.Price.ToString();
            txtQuantity.Value = edititem.Quantity;
            bntAddOrUpdate.Text = "Cập Nhật";
            isUpdating = true;
        }

        private void bntImport_Click(object sender, EventArgs e)
        {
            if (CheckValidate())
            {
                Order order = CreateOrder();
                OrderService service = new OrderService();
                Transaction t = CreateTransaction();
                service.Imports(order, t);
                ShowInfomationBox("Đơn hàng đã được cập  nhật."," Nhập Hàng");
                if (chkContinuosAdding.Checked)
                {
                    ResetForm(true);
                }
                else
                this.Close();
            }
        }

        private bool CheckValidate()
        {
            return base.CheckEmpty(txtOrderCode, "Vui lòng nhập mã hóa đơn");
        }

        

        private Transaction CreateTransaction()
        {
            Transaction t = new Transaction()
            {
                CustomerId = Convert.ToInt32(ddlCustomer.SelectedValue),
                Amount = string.IsNullOrEmpty(txtDeposit.Text) ? 0 : Convert.ToDecimal(txtDeposit.Text),
                StaffId = SessionManager.CurrentUser.Id,
                Type = TransactionTypes.Payment.ToString()
            };
            return t;
        }

        private Order CreateOrder()
        {
            Order order = new Order()
            {
                Cost = Convert.ToDecimal(lblTotal.Text),
                CustomerId = Convert.ToInt32(ddlCustomer.SelectedValue),
                Date = calOrderDate.SelectedDate,
                Deposite = string.IsNullOrEmpty(txtDeposit.Text) ? 0 : Convert.ToDecimal(txtDeposit.Text),
                OrderDetails = new EntityCollection<OrderDetail>(),
                ShippingCost = 0,
                StaffId = SessionManager.CurrentUser.Id,
                Tax = 0,
                TotalCost = Convert.ToDecimal(lblTotal.Text),
                Type = OrderTypes.Buying.ToString(),
                Created = DateTime.Now,
                OrderCode = txtOrderCode.Text
            };

            foreach (var p in _details)
            {
                order.OrderDetails.Add(new OrderDetail()
                {
                    ProductId = p.ProductId,
                    Quantity = p.Quantity,
                    Costs = p.Price
                });

            };


            return order;
        }

        private void WarehouseAddIemForm_Validating(object sender, CancelEventArgs e)
        {
            
        }

      
    }
}
